<template>
  <div class="container">
    <div class="post-edit-page">
      <!-- 页面头部 -->
      <div class="page-header">
        <h1 class="page-title">{{ isNewPost ? '创建新文章' : '编辑文章' }}</h1>
        <div class="page-actions">
          <el-button @click="goBack" plain>
            <el-icon>
              <ArrowLeft />
            </el-icon>返回
          </el-button>
          <el-button type="primary" @click="savePost" :loading="saving">
            <el-icon>
              <Check />
            </el-icon>发布
          </el-button>
        </div>
      </div>

      <div class="edit-form">
        <!-- 标题输入 -->
        <div class="form-group">
          <label for="post-title">文章标题</label>
          <el-input v-model="postForm.title" placeholder="请输入文章标题" maxlength="100" show-word-limit
            :class="{ 'is-error': errors.title }" />
          <div v-if="errors.title" class="error-message">{{ errors.title }}</div>
        </div>

        <!-- 摘要输入 -->
        <div class="form-group">
          <label for="post-summary">文章摘要</label>
          <el-input v-model="postForm.summary" type="textarea" :rows="3" placeholder="请输入文章摘要" maxlength="200"
            show-word-limit :class="{ 'is-error': errors.summary }" />
          <div v-if="errors.summary" class="error-message">{{ errors.summary }}</div>
        </div>

        <!-- 标签选择 -->
        <div class="form-group">
          <label>文章标签</label>
          <div class="tags-header">
            <span class="tags-count">已选择 {{ postForm.tags.length }} 个标签</span>
            <el-button v-if="postForm.tags.length > 0" link @click="clearTags" class="clear-tags-btn">清除所有标签</el-button>
          </div>
          <div class="tags-container">
            <el-tag v-for="tag in availableTags" :key="tag.id" :class="{ 'is-selected': isTagSelected(tag) }"
              @click="toggleTag(tag)" class="clickable-tag">
              {{ tag.tagName }}
              <span class="tag-count" v-if="tag.useCount">({{ tag.useCount }})</span>
            </el-tag>
          </div>
          <div v-if="errors.tags" class="error-message">{{ errors.tags }}</div>
        </div>

        <!-- Markdown编辑器 -->
        <div class="form-group">
          <div class="content-header">
            <label for="post-content">文章内容</label>
            <el-button type="info" link @click="showMarkdownHelp = true">
              <el-icon>
                <QuestionFilled />
              </el-icon>
              Markdown 语法帮助
            </el-button>
          </div>
          <div class="editor-container">
            <v-md-editor v-model="postForm.content" height="600px" @save="savePost" :toolbar="toolbars"
              :include-level="[1, 2, 3, 4, 5, 6]" :disabled-menus="[]" @upload-image="handleUploadImage" />
          </div>
          <div v-if="errors.content" class="error-message">{{ errors.content }}</div>
        </div>

        <!-- Markdown帮助对话框 -->
        <el-dialog v-model="showMarkdownHelp" title="Markdown 语法指南" width="90%" class="markdown-help-dialog">
          <div class="markdown-help">
            <el-tabs>
              <el-tab-pane label="基础语法">
                <div class="help-section">
                  <h3>文本格式化</h3>
                  <div class="help-grid">
                    <div class="help-item">
                      <div class="syntax">**粗体文本**</div>
                      <div class="preview"><strong>粗体文本</strong></div>
                    </div>
                    <div class="help-item">
                      <div class="syntax">*斜体文本*</div>
                      <div class="preview"><em>斜体文本</em></div>
                    </div>
                    <div class="help-item">
                      <div class="syntax">~~删除线~~</div>
                      <div class="preview"><del>删除线</del></div>
                    </div>
                  </div>
                </div>

                <div class="help-section">
                  <h3>标题</h3>
                  <div class="help-grid">
                    <div class="help-item">
                      <div class="syntax"># 一级标题</div>
                      <div class="preview" style="font-size: 2em; font-weight: bold;">一级标题</div>
                    </div>
                    <div class="help-item">
                      <div class="syntax">## 二级标题</div>
                      <div class="preview" style="font-size: 1.5em; font-weight: bold;">二级标题</div>
                    </div>
                    <div class="help-item">
                      <div class="syntax">### 三级标题</div>
                      <div class="preview" style="font-size: 1.17em; font-weight: bold;">三级标题</div>
                    </div>
                  </div>
                </div>

                <div class="help-section">
                  <h3>列表</h3>
                  <div class="help-grid">
                    <div class="help-item">
                      <div class="syntax">
                        - 无序列表项<br>
                        - 另一个项目
                      </div>
                      <div class="preview">
                        • 无序列表项<br>
                        • 另一个项目
                      </div>
                    </div>
                    <div class="help-item">
                      <div class="syntax">
                        1. 有序列表项<br>
                        2. 第二个项目
                      </div>
                      <div class="preview">
                        1. 有序列表项<br>
                        2. 第二个项目
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>

              <el-tab-pane label="高级语法">
                <div class="help-section">
                  <h3>链接与图片</h3>
                  <div class="help-grid">
                    <div class="help-item">
                      <div class="syntax">[链接文本](URL)</div>
                      <div class="preview"><a href="#">链接文本</a></div>
                    </div>
                    <div class="help-item">
                      <div class="syntax">![图片描述](图片URL)</div>
                      <div class="preview">图片将显示在这里</div>
                    </div>
                  </div>
                </div>

                <div class="help-section">
                  <h3>代码</h3>
                  <div class="help-grid">
                    <div class="help-item">
                      <div class="syntax">`行内代码`</div>
                      <div class="preview"><code>行内代码</code></div>
                    </div>
                    <div class="help-item">
                      <div class="syntax">```<br>代码块<br>多行代码<br>```</div>
                      <div class="preview">
                        <pre style="background:#f5f7fa;padding:8px;border-radius:4px">代码块
多行代码</pre>
                      </div>
                    </div>
                  </div>
                </div>

                <div class="help-section">
                  <h3>引用和表格</h3>
                  <div class="help-grid">
                    <div class="help-item">
                      <div class="syntax">> 引用文本</div>
                      <div class="preview" style="border-left:4px solid #ddd;padding-left:1em">引用文本</div>
                    </div>
                    <div class="help-item">
                      <div class="syntax">| 表头 | 表头 |<br>|------|------| <br>| 内容 | 内容 |</div>
                      <div class="preview">
                        <table style="border-collapse:collapse;width:100%">
                          <thead>
                            <tr>
                              <th style="border:1px solid #ddd;padding:4px">表头</th>
                              <th style="border:1px solid #ddd;padding:4px">表头</th>
                            </tr>
                          </thead>
                          <tbody>
                            <tr>
                              <td style="border:1px solid #ddd;padding:4px">内容</td>
                              <td style="border:1px solid #ddd;padding:4px">内容</td>
                            </tr>
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getTagsList } from '../api/tags'
import { getPostDetailById } from '../api/post'
import { uploadFile } from '../api/file'
import { saveOrUpdate } from '../api/post'
import {
  ArrowLeft,
  Check,
  QuestionFilled // 添加帮助图标
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 基础配置
const toolbars = [
  'undo',         // 添加撤销
  'redo',         // 添加重做
  'bold',
  'italic',
  'strikethrough', // 添加删除线
  'heading',
  'quote',
  'link',
  'image',
  'code',
  'code-block',   // 添加代码块
  'ordered-list',
  'unordered-list',
  'table',        // 添加表格
  'line',         // 添加分割线
  'preview',      // 添加预览
  'fullscreen'
]

const availableTags = ref([])

// 状态管理
const isNewPost = computed(() => route.name === 'NewPost')
const saving = ref(false)

// 表单数据
const postForm = ref({
  id: null,
  title: '',
  summary: '',
  tags: [], // 存储 tagName 字符串数组，用于提交到后端
  content: ''
})

const errors = ref({
  title: '',
  summary: '',
  tags: '',
  content: ''
})

// 添加帮助对话框状态
const showMarkdownHelp = ref(false)

// 方法
const goBack = () => {
  if (postForm.value.title || postForm.value.summary ||
    postForm.value.content || postForm.value.tags.length > 0) {
    ElMessageBox.confirm('确定要离开吗？未保存的内容将会丢失', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => router.push('/posts'))
      .catch(() => { })
  } else {
    router.push('/posts')
  }
}

const isTagSelected = (tag) => {
  return postForm.value.tags.includes(tag.tagName)
}

const toggleTag = (tag) => {
  const index = postForm.value.tags.indexOf(tag.tagName)
  if (index === -1) {
    postForm.value.tags.push(tag.tagName)
  } else {
    postForm.value.tags.splice(index, 1)
  }
}

const clearTags = () => {
  ElMessageBox.confirm('确定要清除所有已选标签吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      postForm.value.tags = []
      ElMessage.success('已清除所有标签')
    })
    .catch(() => { })
}

const validateForm = () => {
  errors.value = {
    title: '',
    summary: '',
    tags: '',
    content: ''
  }

  if (!postForm.value.title.trim()) errors.value.title = '请输入文章标题'
  if (!postForm.value.summary.trim()) errors.value.summary = '请输入文章摘要'
  if (postForm.value.tags.length === 0) errors.value.tags = '请至少选择一个标签'
  if (!postForm.value.content.trim()) errors.value.content = '请输入文章内容'

  return !Object.values(errors.value).some(error => error)
}

const savePost = async () => {
  if (!validateForm()) {
    ElMessage.error('请完善表单信息')
    return
  }

  const loading = ElLoading.service({
    lock: true,
    text: isNewPost.value ? '发布中...' : '保存中...',
    background: 'rgba(255, 255, 255, 0.7)',
  })
  saving.value = true
  try {
    const submitData = {
      ...postForm.value,
      tagNames: postForm.value.tags // 确保标签数据格式正确
    }
    const res = await saveOrUpdate(submitData)
    if (res.code === 200) {
      ElMessage.success(isNewPost.value ? '文章发布成功' : '文章更新成功')
      router.push('/posts')
    } else {
      throw new Error(res.msg || '操作失败')
    }
  } catch (error) {
    ElMessage.error(error.message || (isNewPost.value ? '发布失败' : '更新失败'))
    console.error('保存文章错误:', error)
  } finally {
    loading.close()
    saving.value = false
  }
}

// 封装图片处理相关的工具函数
const imageUtils = {
  async uploadImage(file) {
    try {
      const res = await uploadFile(file, 1)
      if (res.code === 200) {
        ElMessage.success('图片上传成功')
        return res.data
      }
      throw new Error(res.msg || '图片上传失败')
    } catch (error) {
      console.error('上传图片错误:', error)
      throw error
    }
  }
}

// 处理直接上传图片 - v-md-editor的upload-image事件
const handleUploadImage = async (event, insertImage) => {
  let file = null

  // 如果是v-md-editor的粘贴事件
  if (event instanceof ClipboardEvent) {
    const items = event.clipboardData?.items
    for (const item of items) {
      if (item.type.startsWith('image/')) {
        file = item.getAsFile()
        break
      }
    }
  }
  // 如果是文件选择事件
  else if (event?.target?.files) {
    file = event.target.files[0]
  }
  // 如果直接是文件对象
  else if (event instanceof File) {
    file = event
  }

  if (!file) {
    return
  }

  const loading = ElLoading.service({
    lock: true,
    text: '上传图片中...',
    background: 'rgba(255, 255, 255, 0.7)',
  })

  try {
    const imageUrl = await imageUtils.uploadImage(file)
    insertImage({
      url: imageUrl,
      desc: file.name
    })
  } catch (error) {
    ElMessage.error('图片上传失败')
    console.error('图片上传错误:', error)
  } finally {
    loading.close()
  }
}

onMounted(async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(255, 255, 255, 0.7)',
  })

  try {
    // 获取所有标签
    const param = {
      pageNum: 1,
      pageSize: 1000,
      isAll: true
    }
    const res = await getTagsList(param)
    availableTags.value = res.data.records

    // 如果是编辑模式，获取文章详情
    if (!isNewPost.value && route.params.id) {
      const articleId = parseInt(route.params.id)
      const articleRes = await getPostDetailById(articleId)

      if (articleRes.code === 200 && articleRes.data) {
        const articleData = articleRes.data
        // 设置表单数据
        postForm.value = {
          id: articleData.id,
          title: articleData.title,
          summary: articleData.summary,
          content: articleData.content,
          tags: articleData.tagNames || [] // 使用后端返回的标签名称数组
        }
      } else {
        ElMessage.error('获取文章详情失败')
        router.push('/posts')
      }
    }
  } catch (err) {
    console.error('初始化失败:', err)
    ElMessage.error(err.message || '初始化失败')
    router.push('/posts')
  } finally {
    loading.close()
  }
})

// 在组件销毁时移除事件监听
onUnmounted(() => { })
</script>

<style scoped>
.post-edit-page {
  padding: 2rem 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.page-title {
  font-size: 2rem;
  margin: 0;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}

.tags-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.clickable-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.clickable-tag.is-selected {
  background-color: var(--el-color-primary);
  color: white;
  border-color: var(--el-color-primary);
}

.clear-tags-btn {
  padding: 0;
  height: auto;
  color: var(--el-color-danger);
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 0.3rem;
}

/* 添加 Markdown 帮助样式 */
.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.markdown-help {
  max-height: 70vh;
  overflow-y: auto;
}

.help-section {
  margin-bottom: 2rem;
}

.help-section h3 {
  margin-bottom: 1rem;
  color: var(--el-text-color-primary);
}

.help-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1rem;
}

.help-item {
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  overflow: hidden;
}

.help-item .syntax {
  background: var(--el-fill-color-lighter);
  padding: 12px;
  font-family: monospace;
  color: var(--el-text-color-primary);
}

.help-item .preview {
  padding: 12px;
  border-top: 1px solid var(--el-border-color-lighter);
  background: var(--el-bg-color);
}

:deep(.el-dialog__body) {
  padding: 20px 24px;
}

/* 添加标签计数样式 */
.tag-count {
  margin-left: 4px;
  font-size: 12px;
  opacity: 0.8;
}

/* 添加图片样式 */
:deep(img) {
  max-width: 100%;
  height: auto;
  resize: both;
  overflow: auto;
  border: 1px solid #ddd;
  margin: 10px 0;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }

  .help-grid {
    grid-template-columns: 1fr;
  }

  .markdown-help-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
}
</style>
